package com.tianyi.wz.walkinggame.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tianyi.wz.walkinggame.Constant;
import com.tianyi.wz.walkinggame.R;
import com.tianyi.wz.walkinggame.biz.CsjRewardVideoBiz;
import com.tianyi.wz.walkinggame.biz.IRewardVideoBiz;
import com.tianyi.wz.walkinggame.biz.TbsRewardVideoBiz;
import com.tianyi.wz.walkinggame.views.AdDialog;
import com.wang.avi.AVLoadingIndicatorView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity implements IWXAPIEventHandler {


    @BindView(R.id.pb_loading)
    AVLoadingIndicatorView pbLoading;
    @BindView(R.id.web_container)
    WebView webView;
    @BindView(R.id.ad_box)
    FrameLayout adBox;

    String url;

    AdDialog infoDialog;

    IWXAPI api;

    /**
     * 激活 js 调用，设置 webView 活跃状态
     */
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onResume() {
        super.onResume();
        webView.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
        reloadPage();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        api = WXAPIFactory.createWXAPI(this, Constant.WECHAT.APPID);
        api.registerApp(Constant.WECHAT.APPID);
        //Intent intent = getIntent();
        //url = intent.getStringExtra("url");
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // 将该app注册到微信
                api.registerApp(Constant.WECHAT.APPID);
            }
        }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
        api.handleIntent(getIntent(), this);
        url = Constant.SETTING.INDEX;
        initWebView();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent,this);
    }

    /**
     * 腾讯 X5 加载网页
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView(){
        if(webView != null){

            WebSettings settings = webView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setDomStorageEnabled(true);
            webView.addJavascriptInterface(new AppInterface(this),"appInterface");
            settings.setUserAgentString(settings.getUserAgentString() + " app/android/WalkingGame");
            webView.loadUrl(url);

            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                    webView.loadUrl(s);
                    return true;
                }

                @Override
                public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                    //pbLoading.setVisibility(View.VISIBLE);
                }

                @Override
                public void onPageFinished(WebView webView, String s) {
                    pbLoading.setVisibility(View.GONE);
                }
            });

            webView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView webView, int i) {
                    if (i < 100) {
                        webView.setVisibility(View.GONE);
                    } else {
                        webView.setVisibility(View.VISIBLE);
                    }
                }
            });
        }

    }


    /**
     * 退出界面暂停 webView的活跃
     */
    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
        webView.getSettings().setLightTouchEnabled(false);

    }


    /**
     * 销毁 放置内存泄漏
     */
    @Override
    protected void onDestroy() {
        if (this.webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        } else if(keyCode == KeyEvent.KEYCODE_BACK){
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM) {
            WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp) resp;
            String extraData =launchMiniProResp.extMsg; //对应小程序组件 <button open-type="launchApp"> 中的 app-parameter 属性
            Log.d(MainActivity.class.getName(),extraData);
        }
    }

    class AppInterface{

        public AppInterface(MainActivity activity){
            this.activity = activity;
        }

        MainActivity activity;

        @JavascriptInterface
        public void popAdWithInspire(String userId,String portal,String codeId){
            /*
            Intent i = new Intent(activity,AdActivity.class);
            activity.startActivity(i);
            */

            runOnUiThread(() -> {
                IRewardVideoBiz biz = null;
                if("toutiao".equals(portal)){
                    biz = CsjRewardVideoBiz.getInstance(MainActivity.this,userId,codeId);
                }else if("eqqads".equals(portal)){
                    biz = TbsRewardVideoBiz.getInstance(MainActivity.this,userId,codeId);
                }
                if(biz!=null) {
                    biz.showAd();
                }
            });

        }

        @JavascriptInterface
        public Boolean popAdWithEmbed(String userId,String protal,String url,String codeId){
            runOnUiThread(() -> {
                infoDialog = new AdDialog.Builder(activity,url,userId,codeId,protal).create();
                infoDialog.show();
            });
            /*
            try {
                for (int i = 0; i < 10; i++) {
                    if(infoDialog!=null && infoDialog.getFlag()){
                        break;
                    }
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                Log.e(MainActivity.class.getName(),e.getMessage(),e);
                e.printStackTrace();
            }
            Log.d(MainActivity.class.getName(),"popAdWithEmbed return true");
            */
            return true;

            //CsjBannerBiz.getInstance(activity,adBox,userId,"934147012").showAd();
        }

        @JavascriptInterface
        public void popAdWithWechat(String programId,String programPath){
            try{
                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                req.userName = programId; // 填小程序原始id
                req.path = programPath;                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                //req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;
                api.sendReq(req);
                //ToastCommon.showToast(activity,"打开小程序 " + programId);
            }catch (Exception e){
                Log.e(MainActivity.class.getName(),e.getMessage(),e);
                //ToastCommon.showToast(activity,e.getMessage());
            }
        }

    }

    public void reloadPage(){

        if((infoDialog==null || !infoDialog.isShowing()) && webView!=null){
            //webView.reload();
            webView.loadUrl("javascript:window.apprefresh();");
        }
    }

}

